package controller

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"yak.admin/src/entity"
	"yak.admin/src/middleware"
	"yak.admin/src/module/api/drug/form"
	"yak.admin/src/repository"
	"yak.admin/src/service"
	"yak.admin/src/util"
)

func PageConfig(ctx *gin.Context) {
	repos := repository.DrugReportRepository{}
	user := ctx.MustGet(util.UserKey).(entity.User)
	data := make(map[string]interface{}, 5)
	data["category_labels"] = repos.DrugCategoryLabels()
	data["risk_labels"] = repos.DrugRiskLabels()
	data["address"] = user.Address
	data["company"] = user.Company
	data["phone"] = user.Phone
	data["number"] = util.GetTimeUUID()
	data["sign"] = util.Md5Sign(form.DrugPageConfigKey, data["number"].(string))
	middleware.ResultSuccess(ctx, "药品提交配置信息", data)
}

func Submit(ctx *gin.Context) {
	f := form.DrugSubmitForm{}
	if err := util.DefaultGetValidParams(ctx, &f); err != nil {
		middleware.ResultFail(ctx, err.Error(), nil)
		return
	}
	user := ctx.MustGet(util.UserKey).(entity.User)
	if err := f.Submit(ctx, user); err == nil {
		behavior := service.BehaviorService{}
		behavior.SubmitDrug(user.Province, user.City, user.County)
		// behavior.AddNoticeTimes(user.Province, user.City, user.County, util.TypeDrug)
		middleware.ResultSuccess(ctx, "上报成功", nil)
		return
	} else {
		middleware.ResultFail(ctx, err.Error(), nil)
	}
}

func DrugReport(ctx *gin.Context) {
	repos := repository.DrugReportRepository{}
	id := ctx.DefaultQuery("id", "0")
	i, _ := strconv.Atoi(id)
	middleware.ResultSuccess(ctx, "", map[string]interface{}{
		"list": repos.FindReport(uint(i)),
	})
}

func UploadAnnex(ctx *gin.Context) {
	f := form.ReportDrugAnnexForm{}
	if err := util.DefaultGetValidParams(ctx, &f); err != nil {
		middleware.ResultFail(ctx, err.Error(), nil)
		return
	}
	if filename, err := f.UploadAnnex(ctx); err == nil {
		middleware.ResultSuccess(ctx, "上传成功", map[string]interface{}{"filename": filename})
		return
	} else {
		middleware.ResultFail(ctx, err.Error(), nil)
	}
}
